/**
 * @author tmh
 * @date 2024/10/14 20:07
 * @description
 */
public class T8字符串转换整数atoi {
    public static void main(String[] args) {
        myAtoi("-042");
    }
    public static int myAtoi(String s) {
        s = s.trim();
        if (s.equals("")){
            return 0;
        }
        boolean flag = false;
        if (s.charAt(0) == '-') {
            flag = true;
            s=s.substring(1);
        }else if (s.charAt(0)=='+'){
            s=s.substring(1);
        }
        int result = 0;
        for (int i = 0; i < s.toCharArray().length; i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                int num = s.charAt(i)-'0';
                if (flag){
                    if (result*-1<-Integer.MAX_VALUE/10||(result*-1==-Integer.MAX_VALUE/10&&-1*num<-8)){
                        return Integer.MIN_VALUE;
                    }
                }else if (result>Integer.MAX_VALUE/10||(result==Integer.MAX_VALUE/10&&num>7)){
                    return Integer.MAX_VALUE;
                }
                result=result*10+num;
            }else {
                break;
            }
        }

        if (flag){
            return -1*result;
        }else {
            return result;
        }
    }
}
